<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import * as echarts from "echarts";

// 获取图表 DOM
const chartRef = ref(null);
let myChart = null;

// 组件 props（传递数据）
const props = defineProps({
  chartData: {
    type: Object,
    required: true,
  },
});

// **code 映射 legend 中文名**
const legendMap = {
  '11': '高危',
  '12': '中危',
  '13': '一般',
};

// **默认选中所有 legend**
const selectedCodes = ref(Object.keys(legendMap));

// **初始化 ECharts**
const initChart = () => {
  if (!chartRef.value) return;

  if (myChart) {
    myChart.dispose();
  }
  myChart = echarts.init(chartRef.value);

  updateChart();
};

// **更新图表数据**
const updateChart = () => {
  if (!myChart) return;

  // **获取所有 legend 中文名**
  const legendNames = Object.values(legendMap);

  // **筛选选中的数据**
  const selectedData = props.chartData.series.filter(s => selectedCodes.value.includes(s.code));

  // **xAxis 显示选中的 `name`**
  const xAxisData = [...new Set(selectedData.map(s => s.name))];

  // **构造 `series`，按 `code` 进行分组**
  const series = selectedCodes.value.map(code => {
    const dataMap = new Map(selectedData.filter(s => s.code === code).map(s => [s.name, s.count]));
    return {
      name: legendMap[code], // 动态设置系列的名称
      type: "bar",
      data: xAxisData.map(name => dataMap.get(name) || 0), // 处理缺失数据
    };
  });

  const option = {
    title: { text: "ECharts Legend 过滤示例" },
    tooltip: { trigger: "axis" },
    legend: {
      data: legendNames, // **显示 legend 中文名称**
      selected: Object.fromEntries(
        legendNames.map(name => [name, selectedCodes.value.includes(getCodeByName(name))])
      ),
      top: 20, // **调整 legend 位置**
    },
    grid: { top: 60, left: 50, right: 50, bottom: 50 },
    xAxis: { type: "category", data: xAxisData },
    yAxis: { type: "value" },
    series: series,
  };
console.log(option)
  myChart.setOption(option);

  // **监听 legend 点击事件**
  myChart.on("legendselectchanged", (params) => {
    console.log(params)
    selectedCodes.value = Object.keys(params.selected)
      .filter(name => params.selected[name])
      .map(getCodeByName); // **转换回 code**
    updateChart();
  });
};

// **根据 legend 中文名获取 code**
const getCodeByName = (name) => Object.keys(legendMap).find(code => legendMap[code] === name);

// **监听数据变化，自动更新**
watch(() => props.chartData, initChart, { deep: true });

onMounted(initChart);
</script>

<style scoped>
.chart-container {
  width: 600px;
  height: 400px;
}
</style>